﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using GCC.APIContainer.Utilities;
using GCC.Container.Abstracts;
using GCC.Container.Models;

using Microsoft.AspNetCore.Mvc;

using tcm.entity;
using tcm.entity.System;
using tcm.Filters;
using tcm.request.System;
using tcm.utils;

namespace tcm.Controller.SystemManage
{
    [ApiController]//记住这个单词
    [Route("tcm/sysrole")]//记住这个
    public class SysRoleController : GCCAPIControllerBase
    {
        private readonly AbsGCCContext _context;
        public SysRoleController(AbsGCCContext context) : base(context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取系统角色管理
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlist")]
        [TCMAuth(permission: "system:role:list")]
        public DataResponse<List<SysRole>> GetList([FromQuery] SysRoleRequest request)
        {
            var dbres = GCCEntrance.DBManager!.LocalDB!.Select<SysRole>()
               .WhereIf(!string.IsNullOrWhiteSpace(request.role_name), item => item.role_name.Contains(request.role_name!))
               .WhereIf(request.status.HasValue, item => item.status==request.status.Value!)
               .Where(x=>x.is_delete==0)
               .Count(out var count)
               .Page(request.PageIndex ?? 1, request.PageSize!=0 ? request.PageSize : int.MaxValue)
               .OrderByDescending(x => x.create_date)
               .ToList();

            return HandleData(dbres, count);
        }

        /// <summary>
        /// 查询角色详情
        /// </summary>
        /// <returns></returns>
        [HttpGet("{id}")]
        public DataResponse<SysRole> GetSysRole([FromRoute] long id)
        {
            var role = GCCEntrance.DBManager!.LocalDB!.Queryable<SysRole>().Where(x => x.id==id).First();

            if (role!=null)
            {
                var menus =GCCEntrance.DBManager!.LocalDB!.Select<SysMenu,SysRoleMenu>().Where((m,rm) => m.id==rm.menu_id && rm.role_id==role.id).ToList();

                if (menus!=null)
                {
                    role.menuIds=string.Join(",",menus.Select(x=>x.id).ToList());
                }            
            }

            return HandleData(role);
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <returns></returns>
        [HttpPost("add")]
        [TCMAuth(permission: "system:role:add")]
        public DataResponse<bool> AddSysRole([FromBody] SysRoleDto request)
        {
            var saveRes = false;
         
            GCCEntrance.DBManager!.LocalDB!.Transaction(() =>
            {
                _=request.Create(_context, HttpContext.GetToken());
                var info = BeanUtils.copy<SysRole, SysRoleDto>(request);
                info.id=request.id;
                info.role_name=request.role_name;
                info.role_key=request.role_key;
                info.remark=request.remark;
                info.is_delete=0;
                info.create_date=request.create_date;
                info.create_by=request.create_by;
                info.update_by=request.update_by;
                info.update_date=request.update_date;
                if (GCCEntrance.DBManager!.LocalDB!.Insert(info).ExecuteAffrows() != 1)
                {
                    throw new Exception();
                }
                saveRes=true;
            });

            //更新权限
            if (saveRes)
            {
                SaveRoleMenu(request);
            }
            return HandleData(saveRes);
        }

        /// <summary>
        /// 保存菜单权限
        /// </summary>
        /// <param name="role_id"></param>
        /// <param name="menuIds"></param>
        private static void SaveRoleMenu(SysRoleDto request)
        {
            var saveRes = false;

            //删除原角色菜单
            var execute = GCCEntrance.DBManager!.LocalDB!.Delete<SysRoleMenu>().Where(x => x.role_id==request.id).ExecuteAffrows();
            if (request.id<=0||string.IsNullOrWhiteSpace(request.menuIds))
                return;
            var ids = SysHelper.SpitIntArrary(request.menuIds);
            // 新增用户与角色管理
            List<SysRoleMenu> sysRoleMenus = new List<SysRoleMenu>();

            //插入新菜单
            foreach (var id in ids)
            {
                sysRoleMenus.Add(new SysRoleMenu()
                {
                    role_id=request.id,
                    menu_id=id,
                    create_by=request.update_by,
                    create_date=request.update_date
                });
            }

            if (sysRoleMenus.Count>0)
                saveRes = GCCEntrance.DBManager!.LocalDB!.Insert<SysRoleMenu>(sysRoleMenus).ExecuteAffrows()>0;
        }

        /// <summary>
        /// 更新角色
        /// </summary>
        /// <returns></returns>
        [HttpPost("update")]
        [TCMAuth(permission: "system:role:update")]
        public DataResponse<bool> UpdateSysRole([FromBody] SysRoleDto request)
        {
            var saveRes = false;
            if (request.id<=0)
                return SystemError<bool>("id为空");

            GCCEntrance.DBManager!.LocalDB!.Transaction(() =>
            {
                _=request.Modify(_context, HttpContext.GetToken());
                saveRes = GCCEntrance.DBManager!.LocalDB!.Update<SysRole>(request.id)
                .Set(item => item.role_sort, request.role_sort)
                .Set(item => item.status, request.status)
                .Set(item => item.role_name, request.role_name)
                .Set(item => item.role_key, request.role_key)
                .Set(item => item.remark, request.remark)
                .Set(item => item.update_by, request.update_by)
                .Set(item => item.update_date, request.update_date)
                .ExecuteAffrows()==1;
            });

            //更新权限
            if (saveRes)
                SaveRoleMenu(request);
            return HandleData(saveRes);
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <returns></returns>
        [HttpDelete("delete/{ids}")]
        [TCMAuth(permission: "system:role:remove")]
        public DataResponse<bool> DeleteSysRole([FromRoute] string ids)
        {
            var saveRes = false;
            if (string.IsNullOrWhiteSpace(ids))
                return SystemError<bool>("id为空");

            var idList = SysHelper.SpitIntArrary(ids);

            saveRes = GCCEntrance.DBManager!.LocalDB!.Update<SysRole>().Where(x => idList.Contains(x.id))
            .Set(item => item.is_delete, 1)
            .ExecuteAffrows()>0;

            return HandleData(saveRes);
        }
    }
}
